//
//  AppDelegate.m
//  SAYAKA_Kitchen
//
//  Created by Rei on 13/07/20.
//  Copyright (c) 2013年 hackathon. All rights reserved.
//

#import "AppDelegate.h"
#import "MasterViewController.h"
#import "DetailListViewController.h"
#import <AudioToolbox/AudioToolbox.h>

@interface AppDelegate() <NSURLConnectionDataDelegate>
@property (assign, nonatomic) BOOL isRegistered;
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    
    
    //push通知登録
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
    
    MasterViewController *masterViewController = [[MasterViewController alloc] initWithNibName:@"MasterViewController" bundle:nil];
    UINavigationController *masterNavigationController = [[UINavigationController alloc] initWithRootViewController:masterViewController];
    masterNavigationController.navigationBar.tintColor = [UIColor darkGrayColor];
    
    DetailListViewController *detailViewController = [[DetailListViewController alloc] initWithNibName:@"DetailListViewController" bundle:nil];
    UINavigationController *detailNavigationController = [[UINavigationController alloc] initWithRootViewController:detailViewController];
    detailNavigationController.navigationBar.tintColor = [UIColor darkGrayColor];
    
    masterViewController.detailViewController = detailViewController;
    
    self.splitViewController = [[UISplitViewController alloc] init];
    self.splitViewController.delegate = detailViewController;
    self.splitViewController.viewControllers = @[masterNavigationController, detailNavigationController];
    self.window.rootViewController = self.splitViewController;
    [self.window makeKeyAndVisible];
#ifdef DEBUG
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveRemoteNotification:) name:@"testOrder" object:nil];
#endif
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


#pragma mark -
#pragma mark Register RemoteNotifications Delegate
//登録正常完了時
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"register success");
    [self sendProviderDeviceToken:deviceToken];
    self.isRegistered = YES;
}

//サーバーにトークンを送信する
- (void)sendProviderDeviceToken:(NSData *)deviceToken {
    
    NSMutableString *jsonString = [NSMutableString string];
    [jsonString appendString:@"{\"apnstokenregist\":{\"a_token_id\":\""];
    [jsonString appendString:[NSString stringWithFormat:@"%@", deviceToken]];
    [jsonString appendString:@"\"}}"];
    NSData *sendData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.xxx.xxx.jp"]];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:sendData];
    [NSURLConnection connectionWithRequest:request
                                  delegate:self];
}

//登録失敗時
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"error: %@", [error localizedDescription]);
    
}

//Push通知データの受信
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    AudioServicesPlaySystemSound(1010);
    //注文がきたことをMasterViewControllerに通知
    NSInteger tableNumber = (NSInteger)[userInfo objectForKey:@"table_number"];
    NSDictionary *tableDict = [NSDictionary dictionaryWithObject:[NSNumber numberWithInteger:tableNumber] forKey:@"table_number"];
    NSNotification *recieveOrderNotification = [NSNotification notificationWithName:@"RecieveOrder" object:self userInfo:tableDict];
    [[NSNotificationCenter defaultCenter] postNotification:recieveOrderNotification];
    
    //注文内容は保持しておく
    NSNotification *itmeNotification = [NSNotification notificationWithName:@"newOrderArrival" object:self userInfo:userInfo];
    [[NSNotificationCenter defaultCenter] postNotification:itmeNotification];
}

#ifdef DEBUG
- (void) didReceiveRemoteNotification:(NSNotification *)notification {
    AudioServicesPlaySystemSound(1010);
    //注文がきたことをMasterViewControllerに通知
    NSDictionary *userInfo = [notification userInfo];
    NSInteger tableNumber = [[userInfo valueForKey:@"table_number"] integerValue];
    NSDictionary *tableDict = [NSDictionary dictionaryWithObject:[NSNumber numberWithInteger:tableNumber] forKey:@"table_number"];
    NSNotification *recieveOrderNotification = [NSNotification notificationWithName:@"RecieveOrder" object:self userInfo:tableDict];
    [[NSNotificationCenter defaultCenter] postNotification:recieveOrderNotification];
    
    //注文内容は保持しておく
    NSNotification *itmeNotification = [NSNotification notificationWithName:@"newOrderArrival" object:self userInfo:userInfo];
    [[NSNotificationCenter defaultCenter] postNotification:itmeNotification];
}
#endif

#pragma mark -
#pragma mark NSURLConnection Delegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    
}
@end